#!/usr/bin/env Rscript

packages <- c('shiny', 'shinyjs', 'V8', 'dplyr', 'dbplyr', 'pool', 'tidyr', 'ggplot2', 'Hmisc', 'RSQLite', 'markdown')
missing.packages <- setdiff(packages, rownames(installed.packages()))
if (length(missing.packages) > 0) {
    cat(c('The following packages will be installed:\n\t', missing.packages, '\n'))
    install.packages(missing.packages, repos="http://cran.r-project.org")
}

library(shiny)

# determine plannerarena directory
args <- commandArgs(trailingOnly = FALSE)
file.arg.name <- "--file="
script.name <- sub(file.arg.name, "", args[grep(file.arg.name, args)])
# directory name containing this script
script.dir <- dirname(normalizePath(script.name))
if (file.exists(paste0(script.dir,"/server.R"))) {
    # if "server.R" exists in the same dir, then this is the app dir
    appDir <- script.dir
} else {
    # otherwise, assume this script is installed in ${prefix}/bin and
    # plannerarena is installed in ${prefix}/share/ompl/plannerarena
    appDir <- normalizePath(paste0(script.dir,"/../share/ompl/plannerarena"))
}

# open plannerarena in the browser
launch.browser <- strtoi(Sys.getenv("OMPL_PLANNERARENA_LAUNCH_BROWSER", "0"))
runApp(appDir,
    host = Sys.getenv("OMPL_PLANNERARENA_HOST", "127.0.0.1"),
    port = strtoi(Sys.getenv("OMPL_PLANNERARENA_PORT", "8888")),
    launch.browser = launch.browser)
